package sk.naive.talker;

import sk.naive.talker.persistence.*;
import sk.naive.talker.props.*;
import sk.naive.talker.server.*;

import java.rmi.RemoteException;
import java.util.*;

/**
 * Board containing posted messages.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.22 $ $Date: 2007-05-07 10:34:20 $
 */
public class Board implements PersistentObject {
	public static final String BPROP_ID = "id";
	public static final String BPROP_NAME = "name";
	public static final String BPROP_ORDER = "sortOrder";
	public static final String BPROP_EDITORS = "editors";
	private List<Text> texts;
	private Set<Integer> editors;

	private PersistentPropertyStoreImpl store;

	public Board(Integer id, BoardFactory bf) {
		store = new PersistentPropertyStoreImpl(id, bf.getPropertyConfiguration());
	}

	public void init() throws PersistenceException, RemoteException {
		texts = new DbLayer().loadTexts(getId(), TextRelation.BOARD_POST, getOrder());
		editors = (Set<Integer>) get(BPROP_EDITORS);
	}

	public String getName() {
		return (String) getProperties().get(BPROP_NAME);
	}

	public List<Text> texts() {
		return texts;
	}

	public String getOrder() {
		return (String) get(BPROP_ORDER);
	}

	public void remove(Text text) throws PersistenceException {
		text.remove();
		texts.remove(text);
	}

	public void add(Text text) {
		if (getOrder().equals(SortOrderProperty.DESC)) {
			texts.add(0, text);
		} else {
			texts.add(text);
		}
	}

	public void clear() throws PersistenceException {
		for (Iterator<Text> i = texts.iterator(); i.hasNext(); ) {
			Text t = i.next();
			i.remove();
			remove(t);
		}
	}

	public Set<Integer> getEditors() {
		return editors;
	}

	public boolean isEditor(User user) {
		return editors.contains(user.getId());
	}

	public void addEditor(User user) throws PropertyStoreException {
		editors.add(user.getId());
		set(BPROP_EDITORS, editors);
	}

	public void removeEditor(User user) throws PropertyStoreException {
		editors.remove(user.getId());
		set(BPROP_EDITORS, editors);
	}

	public Integer getId() {
		return store.getId();
	}

	public void setStoredValue(String key, String value) throws PropertyStoreException {
		store.setStoredValue(key, value);
	}

	public Object get(String property) {
		return store.get(property);
	}

	public void set(String property, Object value) throws PropertyStoreException {
		store.set(property, value);
	}

	public Map<String,Object> getProperties() {
		return store.getProperties();
	}

	public Property getProperty(String key) {
		return store.getProperty(key);
	}
}
